'use strict';

const Controller = require('./baseController');
const uuid = require('node-uuid');

class membersController extends Controller {
	//保存
	async save() {
		const ctx = this.ctx;
		var body = ctx.request.body
		console.log('body', body);
		if(!body.user_name){
			this.fail('请输入账号');
			return;
		}else if(!body.password){
			this.fail('请输入密码');
			return;
		}
		//调用保存方法
		body.key = uuid.v1();
		const res = await ctx.service.members.save(body);
		
		console.log('res', res);
		if (res.code == '200') {
			this.success(res.data);
		} else {
			this.fail(res.msg);
		}
	}
	//获取用户详情
	async info() {
		console.log('info');
		const ctx = this.ctx;
		var body = ctx.request.body
		let params = {
			key: body.key,
		}
		if(params.key){
			const user = await ctx.service.members.findOne(params);
			if(user){
				this.success(user);
			}else{
				this.needLogin();
			}
		}else{
			this.needLogin();
		}
	}
	//用户登录接口
	async login() {
		console.log('login');
		const ctx = this.ctx;
		var body = ctx.request.body;
		let params = {
			user_name: body.user_name,
			password: body.password
		}
		if(!params.user_name){
			this.fail('请输入账号');
			return;
		}else if(!params.password){
			this.fail('请输入密码');
			return;
		}
		var user = await ctx.service.members.findOne(params);
		if(user){
			let editParams = {
				id: user.id,
				key:  uuid.v1()
			}
			await ctx.service.members.update(editParams);
			user.key = editParams.key;
		}
		
		// console.log('user',user); 
		if(user){
			this.success(user);
		}else{
			this.fail('账号或密码错误');
		}
	}

	//更新用户信息
	async update() {
		console.log('info');
		const ctx = this.ctx;
		var body = ctx.request.body

		let params = {};
		
		if(body.nick_name){
			params.nick_name = body.nick_name;
		}
		if(body.brief){
			params.brief = body.brief;
		}
		if(body.key){
			const user = await ctx.service.members.findOne({key:body.key});
			if(user){
				params.id = user.id;
				await ctx.service.members.update(params);
				this.success({});
			}else{
				this.needLogin();
			}
		}else{
			this.needLogin();
		}
	}


}

module.exports = membersController;